import 'package:flutter/material.dart';
import 'package:flame/game.dart';
import 'package:flame/components.dart';
import 'package:flame/events.dart';
import 'dart:math' as math;
import 'package:vector_math/vector_math_64.dart' as vm;
import 'models.dart';

class ApartmentGame3DPage extends StatefulWidget {
  const ApartmentGame3DPage({super.key});

  @override
  State<ApartmentGame3DPage> createState() => _ApartmentGame3DPageState();
}

class _ApartmentGame3DPageState extends State<ApartmentGame3DPage> {
  late ApartmentGame3D game;

  @override
  void initState() {
    super.initState();
    game = ApartmentGame3D();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: Stack(
        children: [
          // 游戏区域
          GameWidget<ApartmentGame3D>.controlled(
            gameFactory: () => game,
          ),
          
          // UI覆盖层
          Positioned(
            top: 20,
            left: 20,
            child: Container(
              padding: const EdgeInsets.all(15),
              decoration: BoxDecoration(
                color: Colors.black54,
                borderRadius: BorderRadius.circular(10),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Text(
                    '3D公寓游戏',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const SizedBox(height: 5),
                  Text(
                    '玩家房间: 301',
                    style: const TextStyle(color: Colors.white, fontSize: 14),
                  ),
                  Text(
                    '当前楼层: 3',
                    style: const TextStyle(color: Colors.white, fontSize: 14),
                  ),
                  const SizedBox(height: 10),
                  const Text(
                    '控制说明：\n'
                    '• 方向键：移动\n'
                    '• 双指拖动：旋转视角\n'
                    '• 双指缩放：缩放视角',
                    style: TextStyle(color: Colors.white70, fontSize: 12),
                  ),
                ],
              ),
            ),
          ),
          
          // 返回按钮
          Positioned(
            top: 20,
            right: 20,
            child: GestureDetector(
              onTap: () => Navigator.pop(context),
              child: Container(
                padding: const EdgeInsets.all(10),
                decoration: BoxDecoration(
                  color: Colors.red.withOpacity(0.8),
                  borderRadius: BorderRadius.circular(10),
                ),
                child: const Icon(
                  Icons.arrow_back,
                  color: Colors.white,
                  size: 24,
                ),
              ),
            ),
          ),
          
          // 控制按钮
          Positioned(
            bottom: 20,
            left: 20,
            child: _buildControlButtons(),
          ),
        ],
      ),
    );
  }
  
  Widget _buildControlButtons() {
    return Container(
      width: 200,
      height: 200,
      child: Stack(
        children: [
          // 方向键背景
          Positioned(
            left: 50,
            top: 50,
            child: Container(
              width: 100,
              height: 100,
              decoration: BoxDecoration(
                color: Colors.black26,
                borderRadius: BorderRadius.circular(10),
              ),
            ),
          ),
          // 上
          Positioned(
            left: 70,
            top: 30,
            child: GestureDetector(
              onTapDown: (_) => game.isMovingForward = true,
              onTapUp: (_) => game.isMovingForward = false,
              onTapCancel: () => game.isMovingForward = false,
              child: Container(
                width: 60,
                height: 40,
                decoration: BoxDecoration(
                  color: Colors.blue.withOpacity(0.7),
                  borderRadius: BorderRadius.circular(5),
                ),
                child: const Icon(Icons.arrow_upward, color: Colors.white),
              ),
            ),
          ),
          // 下
          Positioned(
            left: 70,
            top: 130,
            child: GestureDetector(
              onTapDown: (_) => game.isMovingBackward = true,
              onTapUp: (_) => game.isMovingBackward = false,
              onTapCancel: () => game.isMovingBackward = false,
              child: Container(
                width: 60,
                height: 40,
                decoration: BoxDecoration(
                  color: Colors.blue.withOpacity(0.7),
                  borderRadius: BorderRadius.circular(5),
                ),
                child: const Icon(Icons.arrow_downward, color: Colors.white),
              ),
            ),
          ),
          // 左
          Positioned(
            left: 20,
            top: 80,
            child: GestureDetector(
              onTapDown: (_) => game.isMovingLeft = true,
              onTapUp: (_) => game.isMovingLeft = false,
              onTapCancel: () => game.isMovingLeft = false,
              child: Container(
                width: 40,
                height: 60,
                decoration: BoxDecoration(
                  color: Colors.blue.withOpacity(0.7),
                  borderRadius: BorderRadius.circular(5),
                ),
                child: const Icon(Icons.arrow_back, color: Colors.white),
              ),
            ),
          ),
          // 右
          Positioned(
            left: 140,
            top: 80,
            child: GestureDetector(
              onTapDown: (_) => game.isMovingRight = true,
              onTapUp: (_) => game.isMovingRight = false,
              onTapCancel: () => game.isMovingRight = false,
              child: Container(
                width: 40,
                height: 60,
                decoration: BoxDecoration(
                  color: Colors.blue.withOpacity(0.7),
                  borderRadius: BorderRadius.circular(5),
                ),
                child: const Icon(Icons.arrow_forward, color: Colors.white),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

class ApartmentGame3D extends FlameGame with HasKeyboardHandlerComponents, PanDetector, ScaleDetector {
  late List<Floor> floors;
  late Player3D player;
  Room3D? playerRoom;
  
  // 相机参数
  double cameraAngleX = 0.5; // 俯视角度
  double cameraAngleY = 0.0; // 水平旋转角度
  double cameraDistance = 800.0; // 相机距离
  vm.Vector3 cameraTarget = vm.Vector3.zero(); // 相机目标点
  
  // 游戏常量
  final double roomWidth = 80.0;
  final double roomDepth = 60.0;
  final double roomHeight = 100.0;
  final double floorSpacing = 120.0;
  final int roomsPerFloor = 6;
  
  // 玩家控制
  double moveSpeed = 100.0;
  bool isMovingLeft = false;
  bool isMovingRight = false;
  bool isMovingForward = false;
  bool isMovingBackward = false;
  
  // 随机数生成器
  final math.Random random = math.Random();
  
  @override
  Future<void> onLoad() async {
    super.onLoad();
    
    // 生成公寓结构
    generateApartment();
    
    // 初始化玩家位置（301房间）
    if (playerRoom != null) {
      player.position = vm.Vector3(
        playerRoom!.center.x,
        playerRoom!.position.y + player.height / 2,
        playerRoom!.center.z,
      );
      cameraTarget = player.position.clone();
    }
  }
  
  /// 生成公寓结构（7层楼）
  void generateApartment() {
    floors = [];
    
    for (int floor = 1; floor <= 7; floor++) {
      List<Room3D> rooms = [];
      
      // 计算该楼层的Y位置
      double floorY = (floor - 1) * floorSpacing;
      
      // 生成该楼层的房间
      for (int i = 0; i < roomsPerFloor; i++) {
        String roomNumber = '${floor}0${i + 1}';
        double roomX = (i - roomsPerFloor / 2) * (roomWidth + 20);
        double roomZ = 0;
        
        bool isPlayerRoom = (floor == 3 && i == 0); // 301房间是玩家房间
        
        Room3D room = Room3D(
          roomNumber: roomNumber,
          floorNumber: floor,
          roomIndex: i,
          position: vm.Vector3(roomX, floorY, roomZ),
          width: roomWidth,
          depth: roomDepth,
          height: roomHeight,
          isPlayerRoom: isPlayerRoom,
        );
        
        // 如果不是玩家房间，创建NPC
        if (!isPlayerRoom) {
          room.npc = createNPCForRoom(room);
        } else {
          playerRoom = room;
        }
        
        rooms.add(room);
      }
      
      floors.add(Floor(
        floorNumber: floor,
        rooms: rooms,
      ));
    }
    
    // 初始化玩家
    player = Player3D(
      position: vm.Vector3.zero(),
      currentFloor: 3,
    );
  }
  
  /// 为房间创建NPC
  NPC3D createNPCForRoom(Room3D room) {
    // 随机生成NPC名字
    List<String> names = ['张三', '李四', '王五', '赵六', '钱七', '孙八', 
                          '周九', '吴十', '郑一', '王二', '陈三', '刘四'];
    String name = names[random.nextInt(names.length)];
    
    // 随机生成NPC颜色
    List<Color> colors = [
      Colors.blue,
      Colors.green,
      Colors.orange,
      Colors.purple,
      Colors.pink,
      Colors.teal,
      Colors.amber,
      Colors.cyan,
    ];
    Color npcColor = colors[random.nextInt(colors.length)];
    
    // 生成NPC的活动轨迹（在房间内移动）
    List<ActivityPoint3D> activityPoints = generateActivityPoints(room);
    
    // NPC初始位置在房间中心
    vm.Vector3 npcPosition = vm.Vector3(
      room.center.x,
      room.position.y + 12.5, // NPC高度的一半
      room.center.z,
    );
    
    return NPC3D(
      name: name,
      roomNumber: room.roomNumber,
      color: npcColor,
      position: npcPosition,
      activityPoints: activityPoints,
      moveSpeed: 20.0 + random.nextDouble() * 30.0, // 随机移动速度
    );
  }
  
  /// 生成NPC的活动轨迹点
  List<ActivityPoint3D> generateActivityPoints(Room3D room) {
    List<ActivityPoint3D> points = [];
    
    // 生成3-5个活动点
    int pointCount = 3 + random.nextInt(3);
    
    for (int i = 0; i < pointCount; i++) {
      // 在房间内随机生成活动点（留出边距）
      double margin = 15;
      double pointX = room.position.x + margin + 
          random.nextDouble() * (room.width - margin * 2);
      double pointY = room.position.y + 12.5;
      double pointZ = room.position.z + margin + 
          random.nextDouble() * (room.depth - margin * 2);
      
      // 随机等待时间（1-5秒）
      double waitTime = 1.0 + random.nextDouble() * 4.0;
      
      points.add(ActivityPoint3D(
        position: vm.Vector3(pointX, pointY, pointZ),
        waitTime: waitTime,
        description: _getRandomActivity(),
      ));
    }
    
    return points;
  }
  
  /// 获取随机活动描述
  String _getRandomActivity() {
    List<String> activities = [
      '休息',
      '走动',
      '思考',
      '观察',
      '整理',
      '阅读',
    ];
    return activities[random.nextInt(activities.length)];
  }
  
  @override
  void update(double dt) {
    super.update(dt);
    
    // 更新玩家位置
    vm.Vector3 moveDirection = vm.Vector3.zero();
    if (isMovingLeft) moveDirection = moveDirection + vm.Vector3(-1, 0, 0);
    if (isMovingRight) moveDirection = moveDirection + vm.Vector3(1, 0, 0);
    if (isMovingForward) moveDirection = moveDirection + vm.Vector3(0, 0, -1);
    if (isMovingBackward) moveDirection = moveDirection + vm.Vector3(0, 0, 1);
    
    if (moveDirection.x != 0 || moveDirection.z != 0) {
      // 归一化方向向量
      moveDirection.y = 0; // 确保只在XZ平面移动
      moveDirection = moveDirection.normalized();
      
      player.position = player.position + moveDirection * (moveSpeed * dt);
      player.isFacingRight = moveDirection.x > 0;
      
      // 更新相机目标
      cameraTarget = player.position.clone();
    }
    
    // 更新所有NPC
    for (Floor floor in floors) {
      for (Room3D room in floor.rooms) {
        if (room.npc != null) {
          room.npc!.update(dt);
        }
      }
    }
  }
  
  @override
  void render(Canvas canvas) {
    super.render(canvas);
    
    // 清空画布
    canvas.drawRect(
      Rect.fromLTWH(0, 0, size.x, size.y),
      Paint()..color = const Color(0xFF1a1a2e),
    );
    
    // 计算相机位置
    vm.Vector3 cameraPos = vm.Vector3(
      cameraTarget.x + cameraDistance * math.sin(cameraAngleY) * math.cos(cameraAngleX),
      cameraTarget.y + cameraDistance * math.sin(cameraAngleX),
      cameraTarget.z + cameraDistance * math.cos(cameraAngleY) * math.cos(cameraAngleX),
    );
    
    // 绘制所有楼层和房间
    List<_RenderItem> renderItems = [];
    
    for (Floor floor in floors) {
      for (Room3D room in floor.rooms) {
        // 绘制房间
        _drawRoom3D(canvas, room, cameraPos, renderItems);
        
        // 绘制NPC
        if (room.npc != null) {
          _drawNPC3D(canvas, room.npc!, cameraPos, renderItems);
        }
      }
    }
    
    // 绘制玩家
    _drawPlayer3D(canvas, player, cameraPos, renderItems);
    
    // 按深度排序并绘制
    renderItems.sort((a, b) => b.depth.compareTo(a.depth));
    for (var item in renderItems) {
      item.draw(canvas);
    }
  }
  
  /// 3D到2D投影（等轴测投影）
  Offset project3D(vm.Vector3 point, vm.Vector3 cameraPos) {
    // 简化的等轴测投影
    double scale = 0.5;
    double x = (point.x - point.z) * scale;
    double y = (point.x + point.z) * scale * 0.5 - point.y * scale;
    
    // 转换到屏幕坐标（屏幕中心为原点）
    double screenX = size.x / 2 + x;
    double screenY = size.y / 2 + y;
    
    return Offset(screenX, screenY);
  }
  
  /// 计算深度（用于排序）
  double calculateDepth(vm.Vector3 point, vm.Vector3 cameraPos) {
    return (point - cameraPos).length;
  }
  
  /// 绘制3D房间
  void _drawRoom3D(Canvas canvas, Room3D room, vm.Vector3 cameraPos, List<_RenderItem> renderItems) {
    // 房间的8个顶点
    List<vm.Vector3> vertices = [
      vm.Vector3(room.position.x, room.position.y, room.position.z),
      vm.Vector3(room.position.x + room.width, room.position.y, room.position.z),
      vm.Vector3(room.position.x + room.width, room.position.y, room.position.z + room.depth),
      vm.Vector3(room.position.x, room.position.y, room.position.z + room.depth),
      vm.Vector3(room.position.x, room.position.y + room.height, room.position.z),
      vm.Vector3(room.position.x + room.width, room.position.y + room.height, room.position.z),
      vm.Vector3(room.position.x + room.width, room.position.y + room.height, room.position.z + room.depth),
      vm.Vector3(room.position.x, room.position.y + room.height, room.position.z + room.depth),
    ];
    
    // 绘制房间的6个面
    List<_Face> faces = [
      _Face([vertices[0], vertices[1], vertices[5], vertices[4]], Colors.blue.withOpacity(0.3)), // 前
      _Face([vertices[2], vertices[3], vertices[7], vertices[6]], Colors.blue.withOpacity(0.3)), // 后
      _Face([vertices[0], vertices[3], vertices[7], vertices[4]], Colors.green.withOpacity(0.3)), // 左
      _Face([vertices[1], vertices[2], vertices[6], vertices[5]], Colors.green.withOpacity(0.3)), // 右
      _Face([vertices[4], vertices[5], vertices[6], vertices[7]], Colors.orange.withOpacity(0.3)), // 顶
      _Face([vertices[0], vertices[1], vertices[2], vertices[3]], Colors.brown.withOpacity(0.5)), // 底
    ];
    
    for (var face in faces) {
      vm.Vector3 center = vm.Vector3(
        face.vertices.map((v) => v.x).reduce((a, b) => a + b) / 4,
        face.vertices.map((v) => v.y).reduce((a, b) => a + b) / 4,
        face.vertices.map((v) => v.z).reduce((a, b) => a + b) / 4,
      );
      double depth = calculateDepth(center, cameraPos);
      
      renderItems.add(_RenderItem(
        depth: depth,
        draw: (Canvas c) {
          final path = Path();
          final projected = face.vertices.map((v) => project3D(v, cameraPos)).toList();
          path.moveTo(projected[0].dx, projected[0].dy);
          for (int i = 1; i < projected.length; i++) {
            path.lineTo(projected[i].dx, projected[i].dy);
          }
          path.close();
          
          c.drawPath(
            path,
            Paint()
              ..color = room.isPlayerRoom 
                  ? Colors.lightGreen.withOpacity(0.4)
                  : face.color
              ..style = PaintingStyle.fill,
          );
          
          c.drawPath(
            path,
            Paint()
              ..color = Colors.white.withOpacity(0.5)
              ..style = PaintingStyle.stroke
              ..strokeWidth = 1,
          );
        },
      ));
    }
    
    // 绘制房间号
    vm.Vector3 labelPos = vm.Vector3(
      room.center.x,
      room.position.y + room.height + 10,
      room.center.z,
    );
    Offset labelScreenPos = project3D(labelPos, cameraPos);
    double labelDepth = calculateDepth(labelPos, cameraPos);
    
    renderItems.add(_RenderItem(
      depth: labelDepth,
      draw: (Canvas c) {
        final textPainter = TextPainter(
          text: TextSpan(
            text: room.roomNumber,
            style: TextStyle(
              color: Colors.white,
              fontSize: 12,
              fontWeight: FontWeight.bold,
            ),
          ),
          textDirection: TextDirection.ltr,
        );
        textPainter.layout();
        textPainter.paint(
          c,
          Offset(labelScreenPos.dx - textPainter.width / 2, labelScreenPos.dy),
        );
      },
    ));
  }
  
  /// 绘制3D NPC
  void _drawNPC3D(Canvas canvas, NPC3D npc, vm.Vector3 cameraPos, List<_RenderItem> renderItems) {
    vm.Vector3 top = vm.Vector3(
      npc.position.x,
      npc.position.y + npc.height / 2,
      npc.position.z,
    );
    vm.Vector3 bottom = vm.Vector3(
      npc.position.x,
      npc.position.y - npc.height / 2,
      npc.position.z,
    );
    
    double depth = calculateDepth(npc.position, cameraPos);
    Offset topScreen = project3D(top, cameraPos);
    Offset bottomScreen = project3D(bottom, cameraPos);
    
    renderItems.add(_RenderItem(
      depth: depth,
      draw: (Canvas c) {
        // 绘制NPC身体（圆柱体简化）
        c.drawCircle(
          bottomScreen,
          npc.width / 2,
          Paint()
            ..color = npc.color
            ..style = PaintingStyle.fill,
        );
        
        // 绘制NPC名字
        final textPainter = TextPainter(
          text: TextSpan(
            text: npc.name,
            style: TextStyle(
              color: Colors.white,
              fontSize: 10,
            ),
          ),
          textDirection: TextDirection.ltr,
        );
        textPainter.layout();
        textPainter.paint(
          c,
          Offset(bottomScreen.dx - textPainter.width / 2, bottomScreen.dy - 20),
        );
      },
    ));
  }
  
  /// 绘制3D玩家
  void _drawPlayer3D(Canvas canvas, Player3D player, vm.Vector3 cameraPos, List<_RenderItem> renderItems) {
    vm.Vector3 top = vm.Vector3(
      player.position.x,
      player.position.y + player.height / 2,
      player.position.z,
    );
    vm.Vector3 bottom = vm.Vector3(
      player.position.x,
      player.position.y - player.height / 2,
      player.position.z,
    );
    
    double depth = calculateDepth(player.position, cameraPos);
    Offset topScreen = project3D(top, cameraPos);
    Offset bottomScreen = project3D(bottom, cameraPos);
    
    renderItems.add(_RenderItem(
      depth: depth,
      draw: (Canvas c) {
        // 绘制玩家身体（红色）
        c.drawCircle(
          bottomScreen,
          player.width / 2,
          Paint()
            ..color = Colors.red
            ..style = PaintingStyle.fill,
        );
        
        // 绘制玩家眼睛
        c.drawCircle(
          Offset(bottomScreen.dx + (player.isFacingRight ? 5 : -5), bottomScreen.dy - 5),
          2,
          Paint()
            ..color = Colors.white
            ..style = PaintingStyle.fill,
        );
      },
    ));
  }
  
  // 控制输入
  @override
  bool onPanStart(DragStartInfo info) {
    return true;
  }
  
  @override
  bool onPanUpdate(DragUpdateInfo info) {
    // 双指拖动旋转视角
    cameraAngleY += info.delta.global.x * 0.01;
    cameraAngleX = (cameraAngleX + info.delta.global.y * 0.01).clamp(0.1, math.pi / 2 - 0.1);
    return true;
  }
  
  @override
  bool onScaleUpdate(ScaleUpdateInfo info) {
    // 缩放视角
    double scale = info.scale.global.x; // 使用x分量作为缩放值
    cameraDistance = (cameraDistance / scale).clamp(300.0, 1500.0);
    return true;
  }
  
  // 键盘控制（如果需要）
  void handleKeyPress(String key) {
    switch (key) {
      case 'ArrowLeft':
        isMovingLeft = true;
        break;
      case 'ArrowRight':
        isMovingRight = true;
        break;
      case 'ArrowUp':
        isMovingForward = true;
        break;
      case 'ArrowDown':
        isMovingBackward = true;
        break;
    }
  }
  
  void handleKeyRelease(String key) {
    switch (key) {
      case 'ArrowLeft':
        isMovingLeft = false;
        break;
      case 'ArrowRight':
        isMovingRight = false;
        break;
      case 'ArrowUp':
        isMovingForward = false;
        break;
      case 'ArrowDown':
        isMovingBackward = false;
        break;
    }
  }
}

// 辅助类：用于深度排序渲染
class _RenderItem {
  final double depth;
  final void Function(Canvas) draw;
  
  _RenderItem({required this.depth, required this.draw});
}

// 辅助类：3D面
class _Face {
  final List<vm.Vector3> vertices;
  final Color color;
  
  _Face(this.vertices, this.color);
}

